package fr.ginvest.implementation;

import java.util.Collection;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import fr.ginvest.entity.Article;
import fr.ginvest.entity.Investisseur;
import fr.ginvest.interfaces.ArticleFacadeRemote;

/**
 * Session Bean implementation class ArticleFacade
 */
@Stateless
public class ArticleFacade implements ArticleFacadeRemote {

	@PersistenceContext
	protected EntityManager entityMgr;
	
    public ArticleFacade() {
        
    }
    
    public void deleteArticle(Article a) {
    	a = entityMgr.getReference(Article.class, a.getId());
		entityMgr.remove(a);
    }
	
    public Article addArticle(Article a) {
    	entityMgr.persist(a);
		return a;
    }
    
    public Article updateArticle(Article a) {
    	return entityMgr.merge(a);
    }
    
    public Article findArticleById(Long id) {
    	return entityMgr.find(Article.class, id);
    }

	@SuppressWarnings("unchecked")
	@Override
	public Collection<Article> findAllToutPublic() {
		String queryString = "select model from Article model where model.visibilite = '" + fr.ginvest.entity.Article.Visibilite.TOUT_PUBLIC + "'";
		Query query = entityMgr.createQuery(queryString);
		return query.getResultList();
	}

	@SuppressWarnings("unchecked")
	@Override
	public Collection<Article> findArticleOfInvestisseur(Investisseur invest) {
		String queryString = "select model from Article model where model.investisseur =:invest";
		Query query = entityMgr.createQuery(queryString).setParameter("invest", invest);
		return query.getResultList();
	}

	@SuppressWarnings("unchecked")
	@Override
	public Collection<Article> findAll() {
		String queryString = "select model from Article model";
		Query query = entityMgr.createQuery(queryString);
		return query.getResultList();
	}

}
